package com.yz.crm.system.service.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Service;

import com.yz.common.util.IDUtils;
import com.yz.crm.db.dao.BaseEmployeeRoleMapper;
import com.yz.crm.db.dao.BaseRoleMapper;
import com.yz.crm.db.model.BaseEmployeeRole;
import com.yz.crm.db.model.BaseRole;
import com.yz.crm.db.model.BaseRoleExample;
import com.yz.crm.system.service.RoleService;
/**
 * 角色服务实现
 * */
@Service
public class RoleServiceImpl implements RoleService {

	@Resource
	private SqlSession sqlSession;
	
	@Override
	public BaseRole getRole(String companyId, String code) {
		
		BaseRoleExample exp = new BaseRoleExample();
		exp.createCriteria().andCompanyIdEqualTo(companyId).andCodeEqualTo(code).andIsValidEqualTo(true);
		
		List<BaseRole> roleList = sqlSession.getMapper(BaseRoleMapper.class).selectByExample(exp);
		if (roleList.isEmpty()){
			return null;
		}
		
		return roleList.get(0);
	}

	@Override
	public boolean save(BaseRole role) {
		
		if (role.getId()==null || role.getId().isEmpty()){
			role.setId(IDUtils.getUUID());
		}
		if (role.getCreateDate()==null){
			role.setCreateDate(new Date());
		}
		if (role.getModifyDate()==null){
			role.setModifyDate(role.getCreateDate());
		}
		
		role.setIsValid(true);
		
		return sqlSession.getMapper(BaseRoleMapper.class).insert(role) > 0;
	}
	
	@Override
	public boolean update(BaseRole role) {
		
		if (role.getModifyDate()==null){
			role.setModifyDate(new Date());
		}
		
		return sqlSession.getMapper(BaseRoleMapper.class).updateByPrimaryKey(role) > 0;
	}

	@Override
	public boolean addEmployeeRole(String empolyeeId, String roleId) {
		
		BaseEmployeeRole er = new BaseEmployeeRole();
		er.setCreateDate(new Date());
		er.setId(IDUtils.getUUID());
		er.setEmployeeId(empolyeeId);
		er.setRoleId(roleId);
		
		
		return sqlSession.getMapper(BaseEmployeeRoleMapper.class).insert(er) > 0;
	}

	@Override
	public List<BaseRole> getRoles(String employeeId) {

		return sqlSession.selectList(
				"com.yz.crm.db.dao.BaseRoleMapper.selectEmployeeRoles",
				employeeId);
	}
}
